<template>
	<WithFixedPageContainer
		v-model:page="page"
		@size-change="handleSizeChange"
		@current-change="handleCurrentChange"
	>
		<!-- 搜索表单 -->
		<div class="bg-white p-2 rounded-md">
			<BasicTableFrom :formList="formList" @search="handleSearch">
				<template #menu>
					<el-button type="primary" @click="handleAddNew">新增</el-button>
					<el-button type="primary" @click="handleBatchImport"
						>批量导入</el-button
					>
				</template>
			</BasicTableFrom>
		</div>

		<!-- 表格 -->
		<template #table>
			<div class="h-full overflow-auto">
				<BasicTable
					:data="tableData"
					:option="tableColumns"
					v-model:page="page"
					:table-loading="loading"
				>
					<!-- 车头正面插槽 -->
					<template #vehicleFrontImage="{ row }">
						<el-image
							style="width: 100px; height: 60px"
							:z-index="99999"
							:src="row.vehicleFrontImage"
							:preview-src-list="
								row.vehicleFrontImage ? [row.vehicleFrontImage] : []
							"
							fit="cover"
							:initial-index="0"
						>
							<template #error>
								<div class="image-slot">
									<el-icon><Picture /></el-icon>
								</div>
							</template>
						</el-image>
					</template>

					<!-- 行驶证编号插槽 -->
					<template #drivingLicenseNo="{ row }">
						<el-button type="primary" link>
							{{ row.travelCertNo }}
						</el-button>
					</template>

					<!-- 操作插槽 -->
					<template #menu="{ row }">
						<el-button text type="primary" @click="handleDetail(row)"
							>详情</el-button
						>
						<el-button text type="primary" @click="handleEdit(row)"
							>编辑</el-button
						>
						<el-button text type="danger" @click="handleDelete(row)"
							>报废</el-button
						>
					</template>
				</BasicTable>
			</div>
		</template>

		<!-- 新增/编辑弹窗 -->
		<VehicleDialog
			v-model="dialogVisible"
			:edit-data="editData"
			@success="handleDialogSuccess"
		/>

		<!-- 详情抽屉 -->
		<VehicleDetailDrawer
			v-model="detailDrawerVisible"
			:detail-data="detailData"
		/>
	</WithFixedPageContainer>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Picture } from '@element-plus/icons-vue';
import VehicleDialog from './components/VehicleDialog.vue';
import VehicleDetailDrawer from './components/VehicleDetailDrawer.vue';
import {
	getVehiclePage,
	addVehicle,
	getVehicleById,
	updateVehicle,
	scrapVehicleById,
} from '/@/api/tscompany/vehicle';

// 搜索表单配置
const formList = computed(() => [
	{
		key: 'keyword',
		type: 'input-text',
		label: '关键字:',
		placeholder: '请输入关键字',
		clearable: true,
	},
	{
		key: 'status',
		type: 'select',
		label: '车辆状态:',
		placeholder: '请选择状态',
		clearable: true,
		options: [
			{ label: '正常', value: '1' },
			{ label: '报废', value: '0' },
		],
	},
]);

// 表格列配置
const tableColumns = {
	showOverflowTooltip: true,
	border: true,
	menu: true,
	menuWidth: 180,
	column: [
		// { type: 'index', label: '序号', width: 60, align: 'center' },
		{
			prop: 'vehicleFrontImage',
			label: '车头正面',
			width: 120,
			slot: 'vehicleFrontImage',
		},
		{ prop: 'hphm', label: '车牌号', minWidth: 120 },
		{ prop: 'fleetName', label: '所属车队', minWidth: 120 },
		{ prop: 'ownerName', label: '车主', minWidth: 100 },
		{ prop: 'ownerPhone', label: '车主电话', minWidth: 120 },
		{ prop: 'approvedLoad', label: '检定载重量', minWidth: 120 },
		{ prop: 'totalMass', label: '总质量', minWidth: 120 },
		{
			prop: 'travelCertNo',
			label: '行驶证编号',
			minWidth: 150,
			slot: 'drivingLicenseNo',
		},
		{ prop: 'travelCertExpiry', label: '交验失效日期', minWidth: 150 },
		{ prop: 'transportCertExpiry', label: '商验失效日期', minWidth: 150 },
		{
			prop: 'businessType',
			label: '经营类型',
			minWidth: 120,
			formatter: (row) => {
				return row.businessType === '0'
					? '自营'
					: row.businessType === '1'
						? '联合经营'
						: row.businessType;
			},
		},
		{ prop: 'driverName', label: '准驾司机', minWidth: 100 },
		{ prop: 'driverScore', label: '参与投运(趟)', minWidth: 120 },
		{ prop: 'status', label: '状态', minWidth: 100 },
	],
};

// 分页配置
const page = reactive({
	total: 0,
	currentPage: 1,
	pageSize: 10,
});

// 表格数据
const tableData = ref([]);
const loading = ref(false);

// 搜索参数
const searchParams = reactive({
	keyword: '',
	vehicleStatus: '',
});

// 弹窗相关
const dialogVisible = ref(false);
const editData = ref(null);
const detailDrawerVisible = ref(false);
const detailData = ref(null);

// 方法定义
function handleSearch(data) {
	console.log('Search with:', data);
	searchParams.keyword = data.keyword;
	searchParams.vehicleStatus = data.status;
	page.currentPage = 1; // 重置到第一页
	getList();
}

function handleAddNew() {
	editData.value = null;
	dialogVisible.value = true;
}

function handleBatchImport() {
	console.log('Batch import vehicles');
}

function handleDetail(row) {
	loading.value = true;
	// 通过API获取详细信息
	getVehicleById(row.id)
		.then((response) => {
			if (response.code === 200) {
				detailData.value = response.data;
				detailDrawerVisible.value = true;
			} else {
				ElMessage.error(response.msg || '获取车辆详情失败');
			}
		})
		.catch((error) => {
			console.error('获取车辆详情失败:', error);
			ElMessage.error('获取车辆详情失败，请重试');
		})
		.finally(() => {
			loading.value = false;
		});
}

function handleEdit(row) {
	loading.value = true;
	// 通过API获取详细信息用于编辑
	getVehicleById(row.id)
		.then((response) => {
			if (response.code === 200) {
				editData.value = response.data;
				dialogVisible.value = true;
			} else {
				ElMessage.error(response.msg || '获取车辆详情失败');
			}
		})
		.catch((error) => {
			console.error('获取车辆详情失败:', error);
			ElMessage.error('获取车辆详情失败，请重试');
		})
		.finally(() => {
			loading.value = false;
		});
}

function handleDelete(row) {
	ElMessageBox.confirm('确认要将该车辆标记为报废吗？', '警告', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			// 调用API将车辆标记为报废
			scrapVehicleById(row.id)
				.then((response) => {
					if (response.code === 200) {
						ElMessage.success('操作成功');
						getList();
					} else {
						ElMessage.error(response.msg || '操作失败');
					}
				})
				.catch((error) => {
					console.error('操作失败:', error);
					ElMessage.error('操作失败，请重试');
				});
		})
		.catch(() => {});
}

function handleDialogSuccess(data) {
	addVehicle(data).then((res) => {
		if (res.code == 200 || res.code == 0) {
			// ElMessage.success('操作成功');
			// getList();
		}
	});
	console.log('Form submitted:', data);
	// getList();
}

function handleSizeChange(val) {
	page.pageSize = val;
	getList();
}

function handleCurrentChange(val) {
	page.currentPage = val;
	getList();
}

function getList() {
	loading.value = true;

	// 构建请求参数
	const params = {
		current: page.currentPage,
		size: page.pageSize,
		...searchParams,
	};

	// 调用API获取数据
	getVehiclePage(params)
		.then((response) => {
			if (response.code === 0) {
				// 确保数据中的vehicleFrontImage是有效的URL
				tableData.value = (response.data.records || []).map((item) => {
					// 如果vehicleFrontImage是无效URL，设置为null或默认图片
					if (!item.vehicleFrontImage || item.vehicleFrontImage === '-') {
						item.vehicleFrontImage = '';
					}
					return item;
				});
				page.total = response.data.total || 0;
			} else {
				ElMessage.error(response.msg || '获取车辆列表失败');
			}
		})
		.catch((error) => {
			console.error('获取车辆列表失败:', error);
			ElMessage.error('获取车辆列表失败，请重试');
		})
		.finally(() => {
			loading.value = false;
		});
}

// 初始化加载
onMounted(() => {
	getList();
});
</script>

<style scoped>
.el-input {
	--el-input-width: auto;
}

.image-slot {
	display: flex;
	justify-content: center;
	align-items: center;
	width: 100%;
	height: 100%;
	background: #f5f7fa;
	color: #909399;
}

.image-slot .el-icon {
	font-size: 24px;
}
</style>
